package sealte.port.scanner.run;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import sealte.port.scanner.core.PortScanner;
import sealte.port.scanner.frame.MainFrame;
import sealte.util.UtilTools;

public class MyPortScanner {
	private static MainFrame mf = null;
	public static void main(String[] args){
		mf = new MainFrame();
		mf.getJb_scan().addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				int res = JOptionPane.showConfirmDialog(null, "Are U sure?","Your choice?",JOptionPane.YES_NO_OPTION);
				if(res==0){
					int flag = 0;
					String msg_ip = "";
					String msg_port = "";
					String msg_port1 = "";
					String msg_port2 = "";
					String msg_maxThread = "";
					String ip = mf.getJtf_ip().getText();
					String port1 = mf.getJtf_port1().getText();
					String port2 = mf.getJtf_port2().getText();
					String maxThread = mf.getJtf_maxThread().getText();
					int port1_int = 0;
					int port2_int = 0;
					int maxThread_int = 0;
					if(ip.equals("")){
						ip = "127.0.0.1";
						flag++;
					}else{
						if(UtilTools.isIP(ip)){
							flag++;
						}else{
							msg_ip = "IPv4 is illegal" + " # ";
						}
					}
					if(port1.equals("")){
						port1_int = 0;
						flag++;
					}else{
						if(UtilTools.isNum(port1)){
							port1_int = Integer.parseInt(port1);
							if(port1_int>=0 && port1_int<=65535){
								flag++;
							}else{
								msg_port1 = "start-port should between 0-65535" + " # ";
							}
						}else{
							msg_port1 = "start-port is illegal" + " # ";
						}
					}
					if(port2.equals("")){
						port2_int = 65535;
						flag++;
					}else{
						if(UtilTools.isNum(port2)){
							port2_int = Integer.parseInt(port2);
							if(port2_int>=0 && port2_int<=65535){
								flag++;
							}else{
								msg_port2 = "end-port should between 0-65535" + " # ";
							}
						}else{
							msg_port2 = "end-port is illegal" + " # ";
						}
					}
					if(flag==3){
						if(port1_int <= port2_int){
							flag++;
						}else{
							msg_port = "end-port < start-port" + " # ";
						}
					}
					if(maxThread.equals("")){
						maxThread_int = 500;
						flag++;
					}else{
						if(UtilTools.isNum(maxThread)){
							maxThread_int = Integer.parseInt(maxThread);
							if(maxThread_int>0 && maxThread_int<=500){
								flag++;
							}else{
								msg_maxThread = "MaxThreads should between 1-500";
							}
						}else{
							msg_maxThread = "MaxThreads is illegal";
						}
					}
					if(flag==5){
						PortScanner ps = new PortScanner(mf,ip,port1_int,port2_int,maxThread_int);
						ps.startScan();
					}else{
						JOptionPane.showMessageDialog(null,msg_ip+msg_port1+msg_port2+msg_port+msg_maxThread,
								"WARNING",JOptionPane.WARNING_MESSAGE);
					}
				}
			}
		});
	}
}
